package com.bkgy.modular.hotcoldedgeanalyse.service;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bkgy.excelhandle.PlanExcelHandlerImpl;
import com.bkgy.modular.calsidata.entity.Evaluate;
import com.bkgy.modular.hotcoldedgeanalyse.dao.HotEdgeSameDao;
import com.bkgy.modular.hotcoldedgeanalyse.entity.ExportHotEdgeSame;
import com.bkgy.modular.hotcoldedgeanalyse.entity.HotEdgeSame;
import com.bkgy.modular.hotcoldedgeanalyse.entity.HotStatistics;
import com.bkgy.modular.qms.dao.TbDsjColdNlHotMapper;
import com.bkgy.modular.qms.entity.QmsCurveDataMongo;
import com.bkgy.modular.qms.entity.TbDsjColdNlHot;
import com.bkgy.sys.common.entity.ResultData;
import com.bkgy.util.ExcelUtilsPOI;
import com.bkgy.util.RegexUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotEdgeSameService {

    @Resource
    private HotEdgeSameDao hotEdgeSameDao;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private TbDsjColdNlHotMapper tbDsjColdNlHotMapper;

    public ResultData findDataByPage(JSONObject json) {
        try {
            Integer pageIndex = json.getInteger("pageIndex");
            Integer pageSize = json.getInteger("pageSize");
            if (pageIndex == null || pageSize == null) {
                return ResultData.ResultDataFaultSelf("分页参数没有传", null);
            }
            //查询条件
            String cold_coil_id = null;
            String hot_id = null; // 热卷号
            String dbegin = null;
            String dend = null;
            String ex_thk1 = null;  //产品厚度----开始
            String ex_thk2 = null;  //产品厚度---结束
            String en_wid1 = null;  //原料宽度----开始
            String en_wid2 = null;  //原料宽度----结束
            String en_thk1 = null;  //原料厚度----开始
            String en_thk2 = null;  //原料厚度----结束
            String ele_si1 = null;  //硅含量---开始
            String ele_si2 = null;  //硅含量---结束
            String steelgrade = null;  //钢种
            String shift = null;
            String crew = null;
            JSONObject condition = json.getJSONObject("condition");
            if (!condition.isEmpty()) {
                if (StringUtils.hasText(condition.getString("cold_coil_id"))) {
                    cold_coil_id = condition.getString("cold_coil_id");
                }
                if (StringUtils.hasText(condition.getString("hot_id"))) {
                    hot_id = condition.getString("hot_id");
                }
                if (StringUtils.hasText(condition.getString("dbegin"))) {
                    dbegin = condition.getString("dbegin");
                }
                if (StringUtils.hasText(condition.getString("dend"))) {
                    dend = condition.getString("dend");
                }
                if (StringUtils.hasText(condition.getString("ex_thk1"))) {
                    ex_thk1 = condition.getString("ex_thk1");
                }
                if (StringUtils.hasText(condition.getString("ex_thk2"))) {
                    ex_thk2 = condition.getString("ex_thk2");
                }
                if (StringUtils.hasText(condition.getString("en_wid1"))) {
                    en_wid1 = condition.getString("en_wid1");
                }
                if (StringUtils.hasText(condition.getString("en_wid2"))) {
                    en_wid2 = condition.getString("en_wid2");
                }
                if (StringUtils.hasText(condition.getString("en_thk1"))) {
                    en_thk1 = condition.getString("en_thk1");
                }
                if (StringUtils.hasText(condition.getString("en_thk2"))) {
                    en_thk2 = condition.getString("en_thk2");
                }
                if (StringUtils.hasText(condition.getString("ele_si1"))) {
                    ele_si1 = condition.getString("ele_si1");
                }
                if (StringUtils.hasText(condition.getString("ele_si2"))) {
                    ele_si2 = condition.getString("ele_si2");
                }
                if (StringUtils.hasText(condition.getString("steelgrade"))) {
                    steelgrade = condition.getString("steelgrade");
                }
                if (StringUtils.hasText(condition.getString("shift"))) {
                    shift = condition.getString("shift");
                }
                if (StringUtils.hasText(condition.getString("crew"))) {
                    crew = condition.getString("crew");
                }
            }

            List<HotEdgeSame> list = hotEdgeSameDao.findDataByPage((pageIndex - 1) * pageSize,pageIndex * pageSize, dbegin, dend, ex_thk1, ex_thk2, en_wid1, en_wid2, en_thk1, en_thk2, ele_si1, ele_si2, steelgrade,shift,crew,cold_coil_id,hot_id);
            Integer count = hotEdgeSameDao.findDataCount(dbegin, dend, ex_thk1, ex_thk2, en_wid1, en_wid2, en_thk1, en_thk2, ele_si1, ele_si2, steelgrade,shift,crew,cold_coil_id,hot_id);


            //统计
            //C40
            Double c40_a_abs_lenAll = 0.0;
            Double c40_b_abs_lenAll = 0.0;
            Double c40_c_abs_lenAll = 0.0;
            Double c40_d_abs_lenAll = 0.0;
            Double c40_e_abs_lenAll = 0.0;
            Double c40_f_abs_lenAll = 0.0;
            //W40
            Double w40_a_abs_lenAll = 0.0;
            Double w40_b_abs_lenAll = 0.0;
            Double w40_c_abs_lenAll = 0.0;
            Double w40_d_abs_lenAll = 0.0;
            //边降
            Double edge_a_abs_lenAll = 0.0;
            Double edge_b_abs_lenAll = 0.0;
            Double edge_c_abs_lenAll = 0.0;
            Double edge_d_abs_lenAll = 0.0;
            Double edge_e_abs_lenAll = 0.0;

            c40_a_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getC40_a_abs_len())).mapToDouble(HotEdgeSame::getC40_a_abs_len).sum();
            c40_b_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getC40_b_abs_len())).mapToDouble(HotEdgeSame::getC40_b_abs_len).sum();
            c40_c_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getC40_c_abs_len())).mapToDouble(HotEdgeSame::getC40_c_abs_len).sum();
            c40_d_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getC40_d_abs_len())).mapToDouble(HotEdgeSame::getC40_d_abs_len).sum();
            c40_e_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getC40_e_abs_len())).mapToDouble(HotEdgeSame::getC40_e_abs_len).sum();
            c40_f_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getC40_f_abs_len())).mapToDouble(HotEdgeSame::getC40_f_abs_len).sum();

            w40_a_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getW40_a_abs_len())).mapToDouble(HotEdgeSame::getW40_a_abs_len).sum();
            w40_b_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getW40_b_abs_len())).mapToDouble(HotEdgeSame::getW40_b_abs_len).sum();
            w40_c_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getW40_c_abs_len())).mapToDouble(HotEdgeSame::getW40_c_abs_len).sum();
            w40_d_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getW40_d_abs_len())).mapToDouble(HotEdgeSame::getW40_d_abs_len).sum();

            edge_a_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getEdge_a_abs_len())).mapToDouble(HotEdgeSame::getEdge_a_abs_len).sum();
            edge_b_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getEdge_b_abs_len())).mapToDouble(HotEdgeSame::getEdge_b_abs_len).sum();
            edge_c_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getEdge_c_abs_len())).mapToDouble(HotEdgeSame::getEdge_c_abs_len).sum();
            edge_d_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getEdge_d_abs_len())).mapToDouble(HotEdgeSame::getEdge_d_abs_len).sum();
            edge_e_abs_lenAll = list.stream().filter(x->!StringUtils.isEmpty(x.getEdge_e_abs_len())).mapToDouble(HotEdgeSame::getEdge_e_abs_len).sum();

            //统计赋值
            HotStatistics hotStatistics = new HotStatistics();

            hotStatistics.setC40_a_abs_lenAll(c40_a_abs_lenAll);
            hotStatistics.setC40_b_abs_lenAll(c40_b_abs_lenAll);
            hotStatistics.setC40_c_abs_lenAll(c40_c_abs_lenAll);
            hotStatistics.setC40_d_abs_lenAll(c40_d_abs_lenAll);
            hotStatistics.setC40_e_abs_lenAll(c40_e_abs_lenAll);
            hotStatistics.setC40_f_abs_lenAll(c40_f_abs_lenAll);

            hotStatistics.setW40_a_abs_lenAll(w40_a_abs_lenAll);
            hotStatistics.setW40_b_abs_lenAll(w40_b_abs_lenAll);
            hotStatistics.setW40_c_abs_lenAll(w40_c_abs_lenAll);
            hotStatistics.setW40_d_abs_lenAll(w40_d_abs_lenAll);

            hotStatistics.setEdge_a_abs_lenAll(edge_a_abs_lenAll);
            hotStatistics.setEdge_b_abs_lenAll(edge_b_abs_lenAll);
            hotStatistics.setEdge_c_abs_lenAll(edge_c_abs_lenAll);
            hotStatistics.setEdge_d_abs_lenAll(edge_d_abs_lenAll);
            hotStatistics.setEdge_e_abs_lenAll(edge_e_abs_lenAll);

            return ResultData.ResultDataSuccess(list,count,hotStatistics);
        }catch (Exception e){
            e.printStackTrace();
            return ResultData.ResultDataFaultSelf("查询失败,失败信息为" + e.getMessage(), null);
        }
    }


    public ResultData findLineDataByVolumeNo(JSONObject json){
        JSONObject volumeNos = json.getJSONObject("volumeNos");
        String hot = volumeNos.getString("hot");
        // 将hot字符串拆分成String数组
        String[] split = hot.split(",");
        // 取数组第一个元素和结尾元素判断大写C或者大写P
        if (RegexUtils.isStartWithNumber(hot) && (hot.endsWith("C") || hot.endsWith("P"))) {
            // 构建查询条件
            LambdaQueryWrapper<TbDsjColdNlHot> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TbDsjColdNlHot::getCold_entry_id,hot);

            TbDsjColdNlHot tbDsjColdNlHot = tbDsjColdNlHotMapper.selectOne(queryWrapper);
            if (tbDsjColdNlHot != null) {
                hot = tbDsjColdNlHot.getHot_coil_id();
            }
        }
        String cold = volumeNos.getString("cold");
        if(!StringUtils.hasText(hot)||!StringUtils.hasText(cold)){
            return ResultData.ResultDataFaultSelf(null,"传入卷号为空");
        }
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Map<String,Object>> map1 = new HashMap<>();
        Map<String, Map<String,List<Double>>> map2 = new HashMap<>();
        Query query1=new Query(Criteria.where("volumeNo").is(hot));
        Query query2=new Query(Criteria.where("extid").is(cold));
        List<QmsCurveDataMongo> qmsCurveDataMongos = mongoTemplate.find(query1, QmsCurveDataMongo.class);
        List<Evaluate> evaluates = mongoTemplate.find(query2, Evaluate.class);

        //曲线
        for (QmsCurveDataMongo qmsCurveDataMongo : qmsCurveDataMongos) {
            Map<String,Object> mapValue = new HashMap<>();
            Map<String, List<Double>> originBolg = qmsCurveDataMongo.getOriginBolg();
            if (originBolg != null) {
                List<Double> hsm_crown_c40 = originBolg.get("hsm_crown_c40");
                List<Double> hsm_flatness_wedge40 = originBolg.get("hsm_flatness_wedge40");
                mapValue.put("hsm_crown_c40",hsm_crown_c40);
                mapValue.put("hsm_flatness_wedge40",hsm_flatness_wedge40);
                String volumeNo1 = qmsCurveDataMongo.getVolumeNo();
                if(StringUtils.hasText(volumeNo1)){
                    map1.put(volumeNo1,mapValue);
                }
            }
        }

        for (Evaluate evaluate : evaluates) {
            Map<String,List<Double>> mapValue = new HashMap<>();
            Map<String, List<Double>> edge = evaluate.getEdge();
            List<Double> edm_ds = edge.get("EDM_DS");
            List<Double> edm_ws = edge.get("EDM_WS");
            mapValue.put("EDM_DS",edm_ds);
            mapValue.put("EDM_WS",edm_ws);
            String extid = evaluate.getExtid();
            if(StringUtils.hasText(extid)){
                map2.put(extid,mapValue);
            }
        }
        map.put("blob",map1);
        map.put("edge",map2);
        if(!CollectionUtils.isEmpty(map)){
            return ResultData.ResultDataSuccess(map);
        }
        return ResultData.ResultDataFaultSelf(null,"查询数据为空");
    }


    public void export(JSONObject jsonObject, HttpServletResponse response) {
        // 接收传入参数
        Integer pageSize = jsonObject.getInteger("pageSize");
        Integer pageCount = jsonObject.getInteger("pageCount");
        String fileNames = jsonObject.getString("fileName");

        //查询条件
        String cold_coil_id = null;
        String hot_id = null; // 热卷号
        String dbegin = null;
        String dend = null;
        String ex_thk1 = null;  //产品厚度----开始
        String ex_thk2 = null;  //产品厚度---结束
        String en_wid1 = null;  //原料宽度----开始
        String en_wid2 = null;  //原料宽度----结束
        String en_thk1 = null;  //原料厚度----开始
        String en_thk2 = null;  //原料厚度----结束
        String ele_si1 = null;  //硅含量---开始
        String ele_si2 = null;  //硅含量---结束
        String steelgrade = null;  //钢种
        String shift = null;
        String crew = null;
        JSONObject condition = jsonObject.getJSONObject("condition");
        if (!condition.isEmpty()) {
            if (StringUtils.hasText(condition.getString("cold_coil_id"))) {
                cold_coil_id = condition.getString("cold_coil_id");
            }
            if (StringUtils.hasText(condition.getString("hot_id"))) {
                hot_id = condition.getString("hot_id");
            }
            if (StringUtils.hasText(condition.getString("dbegin"))) {
                dbegin = condition.getString("dbegin");
            }
            if (StringUtils.hasText(condition.getString("dend"))) {
                dend = condition.getString("dend");
            }
            if (StringUtils.hasText(condition.getString("ex_thk1"))) {
                ex_thk1 = condition.getString("ex_thk1");
            }
            if (StringUtils.hasText(condition.getString("ex_thk2"))) {
                ex_thk2 = condition.getString("ex_thk2");
            }
            if (StringUtils.hasText(condition.getString("en_wid1"))) {
                en_wid1 = condition.getString("en_wid1");
            }
            if (StringUtils.hasText(condition.getString("en_wid2"))) {
                en_wid2 = condition.getString("en_wid2");
            }
            if (StringUtils.hasText(condition.getString("en_thk1"))) {
                en_thk1 = condition.getString("en_thk1");
            }
            if (StringUtils.hasText(condition.getString("en_thk2"))) {
                en_thk2 = condition.getString("en_thk2");
            }
            if (StringUtils.hasText(condition.getString("ele_si1"))) {
                ele_si1 = condition.getString("ele_si1");
            }
            if (StringUtils.hasText(condition.getString("ele_si2"))) {
                ele_si2 = condition.getString("ele_si2");
            }
            if (StringUtils.hasText(condition.getString("steelgrade"))) {
                steelgrade = condition.getString("steelgrade");
            }
            if (StringUtils.hasText(condition.getString("shift"))) {
                shift = condition.getString("shift");
            }
            if (StringUtils.hasText(condition.getString("crew"))) {
                crew = condition.getString("crew");
            }



            // 调用service查询出数据
            List<HotEdgeSame> data = null;
            List<ExportHotEdgeSame> list = new ArrayList<>();
            for (int i = 1; i <= pageCount; i++) {
                // 分页去数据库查询数据 这里可以去数据库查询每一页的数据
                data = hotEdgeSameDao.findDataByPage((i - 1) * pageSize, i * pageSize,dbegin, dend, ex_thk1, ex_thk2, en_wid1, en_wid2, en_thk1, en_thk2, ele_si1, ele_si2, steelgrade,shift,crew,cold_coil_id,hot_id);
                if (!data.isEmpty() && data.size() > 0) {
                    for (HotEdgeSame item : data) {
                        ExportHotEdgeSame exportHotEdgeSame = new ExportHotEdgeSame();
                        BeanUtils.copyProperties(item,exportHotEdgeSame);
                        list.add(exportHotEdgeSame);
                    }
                }
            }
            try {
                Map<String,Object> data1 = new HashMap();
                data1.put("data",list);
                File file = ResourceUtils.getFile("classpath:exceltemplate\\热轧冷轧边降分析.xlsx");
                TemplateExportParams templateExportParams = new TemplateExportParams(file.getPath(),false);
                templateExportParams.setDictHandler(new PlanExcelHandlerImpl());
                Workbook workbook = ExcelExportUtil.exportExcel(templateExportParams, data1);
                ExcelUtilsPOI.exportExcel(fileNames,response,workbook);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
